import type { ModalConfig } from '@arco-design/web-vue'
import { Modal } from '@arco-design/web-vue'
import { isFunction, isUndefined } from 'lodash-es'

export class ModalHelper {
  private static defaultConfig: ModalConfig = {
    title: '操作确认',
    content: '请确认操作',
    width: 400,
    okText: '确认',
    cancelText: '取消',
    titleAlign: 'start',
    hideCancel: false,
    simple: false,
    modalClass: 'basic-dialog',
  }

  private static renderTitle = (config: ModalConfig) => {
    return h('div', { class: 'cloud-model__title' }, [
      isFunction(config.title) ? config?.title?.() : config?.title,
    ])
  }

  private static renderContent = (config: ModalConfig) => {
    return h('div', { class: 'cloud-model__content' }, [
      isFunction(config.content) ? config?.content?.() : config?.content,
    ])
  }

  private static onBeforeOk(request?: PromiseFn) {
    return async () => {
      try {
        const flag = await request?.()
        if (isUndefined(flag)) {
          return true
        }
        return flag
      } catch (_: any) {
        return false
      }
    }
  }

  static confirm(config: ModalConfig, request?: PromiseFn) {
    const conf = { ...ModalHelper.defaultConfig, ...config }
    return Modal.error({
      ...conf,
      content: () => ModalHelper.renderContent(conf),
      onBeforeOk: ModalHelper.onBeforeOk(request),
      modalClass: `${conf.modalClass} is-normal`,
    })
  }

  static error(config: ModalConfig, request?: PromiseFn) {
    const conf = { ...ModalHelper.defaultConfig, ...config }
    return Modal.error({
      ...conf,
      title: () => ModalHelper.renderTitle(conf),
      content: () => ModalHelper.renderContent(conf),
      onBeforeOk: ModalHelper.onBeforeOk(request),
      modalClass: `${conf.modalClass} is-danger`,
    })
  }
}
